//
// Embed
//
function Embed(currentId)
{
	this._construct(currentId);
}
Embed.prototype = {
	imgSkinId: '_imgSkinDemo',
	currentId: 1,
	classForum:'_shr_txtFrm',
	classBlog: '_shr_txtBlg',
	classLnk: '_shr_txtLnk',
	autoPlayId: 'shr_btnAut',
	musicBgId: 'shr_btnMubgr',
	strAuto: '_strAuto',
	strNoAuto: '_strNoAuto',
	urlEmbed1: MP3.MP3_URL,
	urlEmbed2: MP3.STATIC_URL + 'skins/mp3_main/',
	xmlUrl: '',
	width: 300,
	height: 61,

	_construct:
		function(currentId) {
		this.xmlUrl = zm('#_strNoAuto').val();
		zm('.' + this.classLnk).click(function() {
			zm(this).select();
		});
		if(currentId)
			this.currentId = currentId;
	},
	changeAutoPlay:
		function(autoPlayId, strAuto, strNoAuto) {
		if (autoPlayId) this.autoPlayId = autoPlayId;
		if (strAuto) this.strAuto = strAuto;
		if (strNoAuto) this.strNoAuto = strNoAuto;
		var chkAutoPlay = zm('#' + this.autoPlayId).attr('checked');
		if (chkAutoPlay) {
			this.autoPlay = 'true';
			this.xmlUrl = zm('#' + this.strAuto).val();
		} else {
			this.autoPlay = 'false';
			this.xmlUrl = zm('#' + this.strNoAuto).val();
		}
		this.setEmbededCode();
	},
	changeMusicBg:
		function(musicBgId, autoPlayId) {
		if (musicBgId) this.musicBgId = musicBgId;
		if (autoPlayId) this.autoPlayId = autoPlayId;
		var chkBackGround = zm('#' + this.musicBgId).attr('checked');
		if (chkBackGround) {
			zm('#' + this.autoPlayId).attr('checked','checked')
			this.changeAutoPlay();
			zm('#' + this.autoPlayId).attr('disabled','disabled');
			this.width = 1;
			this.height = 1;
		} else {
			zm('#' + this.autoPlayId).attr('disabled','');
			this.width = 360;
			this.height = 61;
		}
		this.setEmbededCode();
	},
	setEmbededCode:
		function()
	{
		var self	= this;
		// create forum link
		if (zm('.' + this.classForum).size) {
			zm('.' + this.classForum).attr('readonly', 'readonly');
			zm('.' + this.classForum).val(self.createEmbbedCodeForum(zm('.' + this.classForum).attr('name')));
			zm('.' + this.classForum).click(function() {
				zm(this).select();
			});
		}

		// create blog link
		if (zm('.' + this.classBlog).size) {
			zm('.' + this.classBlog).attr('readonly', 'readonly');
			zm('.' + this.classBlog).val(self.createEmbbedCodeBlog(zm('.' + this.classBlog).attr('name')));
			zm('.' + this.classBlog).click(function() {
				zm(this).select();
			});
		}
	},
	createEmbbedCodeBlog:
		function(type)
	{
		var src	= '';
		switch (type) {
			case 'song':
				src	= this.urlEmbed2 + 'flash/player/mp3Player_skin' + this.currentId + '.swf?xmlurl=' + this.xmlUrl;
				break;
			case 'album':
				this.width	= 400;
				this.height	= 300;
				src	= this.urlEmbed2 + 'flash/embed/zing_mp3_embed_v1.2.swf?xmlURL=' + this.xmlUrl + '&autostart=false';
				break;
			case 'media':
			case 'video':
				this.width	= 400;
				this.height	= 300;
				src	= this.urlEmbed2 + 'flash/embed/zing_mp3_embed_v1.2.swf?xmlURL=' + this.xmlUrl + '&autostart=false';
				break;
		}
		var tpl = '<object width="'+this.width+'" height="'+this.height+'">';
		tpl += '<param name="movie" value="' + src + '" />';
		tpl += '<param name="quality" value="high" />';
		tpl += '<param name="wmode" value="transparent" />';
		tpl += '<embed width="'+this.width+'" height="'+this.height+'" src="' + src + '" quality="high" wmode="transparent" type="application/x-shockwave-flash"></embed>';
		tpl += '</object>';
		tpl	+= '<br />';

		return tpl;
	},
	createEmbbedCodeForum:
		function(type)
	{
		switch (type) {
			case 'song':
				var tpl = '[FLASH]' + this.urlEmbed2 + 'flash/player/mp3Player_skin' + this.currentId + '.swf?xmlurl='  + this.xmlUrl +'[/FLASH]';
				break;
			case 'album':
				var tpl = '[FLASH]' + this.urlEmbed2 + 'flash/embed/zing_mp3_embed_v1.2.swf?xmlURL=' + this.xmlUrl + '&autostart=false[/FLASH]';
				break;
			case 'video':
			case 'media':
				var tpl = '[FLASH]' + this.urlEmbed2 + 'flash/embed/zing_mp3_embed_v1.2.swf?xmlURL=' + this.xmlUrl+ '&autostart=false[/FLASH]';
				break;
		}
		return tpl;
	}
};

//
// Lyrics: View Versions of Lyric
//
var MP3Lyrics = {
	urlRequest: MP3.MP3_URL+'ajax/lyric-v2',
	loading:false,
	_submitNew:false,
	init:
		function () {
		if(zm('#_lyricContainer').size()) {
			zm('._lyricNav').click(function(){
				var regEx = /\/([a-z0-9]+).html/i;
				var match = regEx.exec(location.pathname);
				if(match[1]){
					if(zm('#_lyricContainer'+match[1]).children('div').length<2){
						MP3Lyrics.loadLyrics(match[1], zm(this).attr('rel'));
					}
				}
				return false;
			});
			zm('._lyricSubmit').click(function(){
				MP3Lyrics.submitNew(zm('#_lyricContent'+zm(this).attr('rel')));
				return false;
			});
			zm('._lyricMsgC').click(function(){
				zm('#'+zm(this).attr('rel')).addClass('none');
				return false;
			});
			zm('._lyricNewBtn').click(function(){
				if(Login.show())
					Common.showHide(zm('#'+zm(this).attr('rel')));
				return false;
			});
		}
	},
	loadLyrics:function(songId, shwId){
		zmCore.get(MP3Lyrics.urlRequest+'/lyrics?id='+songId,
		{
			'dataType': 'json'
		},
		function(data) {
			if(!data.is_error){
				for(var i=0; i<data.result.length;i++){
					zm('#_lyricContainer'+songId).append(data.result[i]);
					zm('#_lyric'+songId+'_'+(i+1)).addClass('none');
				}
				zm('._lyricItem').addClass('none');
				if(shwId) zm('#'+shwId).removeClass('none');
				else zm('#_lyric'+songId+'_'+ data.result.length).removeClass('none');
				MP3Lyrics.ctrlHdl();
				MP3Lyrics.initRating();
			}
		});
	},
	initRating:function() {
		if(zm('._lyricVoting').size()) {
			zm('._lyricVoting').each(function(e){
				if(parseInt(zm(this).attr('rel'))>0) {						
					var id = zm(this).attr('id');
					zmCore.getJSON(MP3Lyrics.urlRequest+'/get-rating?id='+id,
					{
						'dataType': 'json'
					},
					function(data) {
						MP3Lyrics.ratingState(id,data.result);
					});
				}
			});
		}
	},
	ratingState:function(id,s){
		if(s!=0) {
			if(zmCore.browser.msie)
				zm("a[name="+zm('#'+id).attr('name')+"]").addClass('voted');
			else 
				zm("a[name='"+zm('#'+id).attr('name')+"']").addClass('voted');
		}
	},
	submitNew:function(obj){
		if(Login.show())
		{
			if (!MP3Lyrics._submitNew)
			{
				var idItem = obj.attr('oid');
				var lyricContainer = '_lyricContainer'+idItem;
				var content = obj.val();
				content = content.trim();
				if(content.length<200){
					MP3Lyrics.msgBox(idItem, 'Lời bài hát cần ít nhất 200 ký tự',true);
				} else if(content.length>4000){
					MP3Lyrics.msgBox(idItem, 'Lời bài hát chỉ cho phép tối đa 4000 ký tự',true);
				}
				else if (idItem) {
					var size = zm('#'+lyricContainer).children('div').length;
					MP3Lyrics._submitNew = true;
					zmCore.post(MP3Lyrics.urlRequest+'/add', 
					{
						'oid': idItem, 
						'content': content,
						'items':size
					},

					{
						'dataType': 'json'
					},
					function(data) {
						MP3Lyrics._submitNew = false;
						if(!data.is_error) {
							zm('#_lyricNewBox'+idItem).remove();
							zm('#_lyricNote'+idItem).remove();
							MP3Lyrics.loadLyrics(idItem);
							MP3Lyrics.msgBox(idItem, 'Lời bài hát đã gởi thành công. Cảm ơn bạn đã nhiệt tình đóng góp',false);
						}
						else MP3Lyrics.msgBox(idItem, data.note, true);
					});
				}
			}
		}
	},
	addScore:function(obj){
		if(Login.show())
		{
			var idItem = obj.attr('id');
			if (!MP3Lyrics.loading && !obj.hasClass('voted')) {
				MP3Lyrics.loading = true;
				zmCore.post(MP3Lyrics.urlRequest+'/add-score', 
				{
					'id': idItem
				},

				{
					'dataType': 'json'
				},
				function(data) {
					Common.msgBox(data.note);
					MP3Lyrics.loading = false;
					MP3Lyrics.ratingState(idItem,data.total);
					zm('#_lyricScore'+data.id).html(data.score);
				});
			}
		}
	},
	msgBox:function(oid,msg,err){
		zm('#_lyricMsg'+oid).html(msg);
		if(err) {
			zm('#_lyricMsgBox'+oid).removeClass('none').addClass('fail');
		} else {
			zm('#_lyricMsgBox'+oid).removeClass('none').addClass('success');
		}
	},
	ctrlHdl:function(){
		if(typeof ZME_widget_mix =='function') ZME_widget_mix();
		else zmCore.addScript(MP3.ME_WIDGET_URL + 'js/zingme_widget_ex_1.7.1.min.js', function () {
			ZME_widget_mix();
		});
		zm('._lyricVoting').click(function(){
			MP3Lyrics.addScore(zm(this));
			return false;
		});
		zm('._lyricNav').click(function(){
			zm('._lyricItem').addClass('none');
			zm('#'+zm(this).attr('rel')).removeClass('none');
			return false;
		});		
	}
};
var ZingPlayer = {
	Error:function(ord){
		MP3Player.loadFail(ord);
	},
	Play:function(arg){
		if(!arg) arg = 0;
		MP3Player.focusItem(arg);
	},
	Next:function(arg){
	},
	Prev:function(arg){
	},
	AdLoad:function(url){
	},
	AdClick:function(url){
	},
	Expand:function(){
		if(zm('#_videoPlayer').size()) {
			zm('#_videoPlayer').addClass('expand');
			zm('.sidebar').css('margin-top', '');
			var playerId = document.getElementById('player')!=null?'player':'oplayer';
			if(zm('#'+playerId).length) {
				setTimeout(new Function("zm('#"+playerId+"').css('width', '950px').css('height', '574px');"),50);
				if((typeof document.getElementById(playerId).resize)=='function') document.getElementById(playerId).resize(950, 574);
			}
			if(MP3.BANNER_OFF!=1) setTimeout(new Function("Ads.changePositionBanner();"),60);
		}
	},
	UnExpand:function(){
		if(zm('#_videoPlayer').size()) {
			zm('#_videoPlayer').removeClass('expand');
			zm('.sidebar').css('margin-top', '-465px');
			var playerId = document.getElementById('player')!=null?'player':'oplayer';
			if((zm('#'+playerId).length)) {
				setTimeout(new Function("zm('#"+playerId+"').css('width', '640px').css('height', '401px');"),50);
				if((typeof document.getElementById(playerId).resize)=='function') document.getElementById(playerId).resize(640, 401);
			}
			if(MP3.BANNER_OFF!=1) setTimeout(new Function("Ads.changePositionBanner();"),60);
		}
	},
	RequireVip:function(){
		return 'Chức năng này chỉ dành cho VIP User';
	},
	VASTurl:function(){
//		return "http://bs.serving-sys.com/BurstingPipe/adServer.bs?cn=is&c=23&pl=VAST&pli=4818528&pi=0&pos=3578&ord=1234&cim=1";
		return MP3.MP3_URL+'ads/vast';
	}
};

var MP3SongPlay = {
	init:function(){
		
	},
	sendReport:function(obj){
		if(Login.show()){
			var notError = true;
			zm('input[name=_reportType]').each(function(){
				if(zm(this).attr('checked')){
					zm(this).attr('checked',false);
					notError = false;
					MP3FeedBack.post(1,zm(this).val(),location.href,MP3SongPlay.hSendReport);
				}
			});
			if(notError) Common.showMsg('_reportMsg', 1, 'Vui lòng chọn nguyên nhân');
		}
	},
	hSendReport:function(data){
		if(!data.is_error) {
			zm('#_btnReportShw').addClass(Common.cssHidden);
			zm('#_reportMsgBox').addClass(Common.cssHidden);
			Common.msgBox(data.note);
		} else Common.showMsg('_reportMsgBox', data.is_error, data.note);
	},
	closeReport:function(){
		zm('#_reportOther').addClass(Common.cssHidden);
		zm('#_btnReportShw').addClass(Common.cssHidden);
	}
};

/* html5 player */
var zPlaylist	= {
	current: -1,
	select:
		function (index)
	{
		this._focusItem(index);
	},
	next:
		function (index)
	{
		var index	= this.current + 1;
		this._focusItem(index);
	},
	previous:
		function (index)
	{
		var index	= this.current - 1;
		this._focusItem(index);
	},
	_focusItem:
		function(index)
	{
		if (zm('#_plContainer').size()) {
			if (index != this.current) {
				zm('#_plContainer').children().removeClass('playing');
				zm('#_plItem' + index).addClass('playing');
			}
			this.current	= index;
		}
	}
}

var MP3Player = {
	idx:-1,
	init:function(){
		if(zm('#_plContainer').size()){
			if(typeof history.pushState =='function') {
				zmCore.addScript(MP3.STATIC_URL_V3 + MP3.SKIN_PATH_V3 + 'js/history.js');
			}
			if(location.hash.search('st=')!=-1){
				var regEx = /st=\d+/i;
				var matchHash = regEx.exec(location.hash);
				if(matchHash){
					location.hash='';
					location.search='?'+matchHash[0];
				}
			}
			zm('._playItem').click(function(){
				MP3Player.playItem(zm(this).attr('rel'));
				_gaq.push(['mp3._trackPageview', '/from-album'+zm(this).attr('href')]);
				return false;
			});
		}
	},
	setUrl:function(idx){
		idx++;
		if(typeof history.pushState =='function')
			History.pushState({
				state:1,
				rand:Math.random()
			}, document.title, "?st="+idx);
		else if(!zmCore.browser.msie) location.hash='st='+idx;
	},
	focusItem:function(arg,play){
		if(zm('#_plContainer').size()){
			if(arg!=MP3Player.idx){
				zm('#_plContainer').children().each(function(){
					zm(this).removeClass('playing');
				});
				zm('#_plItem'+arg).addClass('playing');				
				_gaq.push(['z._trackPageview', zm('#_itemDetail'+arg).attr('href')]);
				_gaq.push(['_trackPageview', zm('#_itemDetail'+arg).attr('href')]);
				if(!play) MP3Player.setUrl(arg);
			}
			MP3Player.idx = arg;
		}
	},
	playItem:function(ord){
		MP3Player.focusItem(ord);
		if(zmCore.browser.msie)
			document.getElementById('oplayer').PlayMedia(ord);
		else {
			document.getElementById('player').PlayMedia(ord);
		}
	},
	loadFail:function(ord){
		var mediaId = '';
		var type = 'song';
		if(zm('#_plContainer').size()){
			mediaId = zm('#_plItem'+ord).attr('rel');
			MP3Player.playItem(ord+1);
			type = 'playlist';
		} else {
			var regEx = /\/([a-z0-9]+).html/i;
			var match = regEx.exec(location.pathname);
			if(match[1]){
				mediaId = match[1];
			}
			if(zm('#_videoPlayer').size()){
				type='video';
			}
		}
		zmCore.get(MP3.LOG_URL + 'log/error404?type='+type+'&id='+mediaId);
	}
};
var MP3Tab = {
	btnId:null,
	init:function(){
		zm('._btnTab').click(function(){
			MP3Tab.btnId = zm(this).attr('id');
			MP3Tab.active();
			return false;
		});
		if(zm('#_reportType').size()){
			zm('#_reportType').change(function(){
				if(zm(this).val()=='-1') zm('#_reportOther').removeClass(Common.cssHidden);
				else zm('#_reportOther').addClass(Common.cssHidden);
			});
		}
		zm('#_reportContent').focus(function(){
			if(zm(this).val()=='Nếu vấn đề bạn gặp phải không có trong danh sách trên, vui lòng nhập thông báo ở đây.') zm(this).val('');
		});
		zm('#_btnReportSubmit').click(function(){
			MP3SongPlay.sendReport(zm(this));
			return false;
		});
		zm('._closeTab').click(function(){
			zm('#'+zm(this).attr('rel')).addClass('none');
			zm('._btnTab').removeClass('active');
			return false;
		});
		zm('#_addFav').click(function(){
			MP3Playlist.isLite = false;
			MP3Playlist.addFav('_addMsg',zm(this));
			zm('._tabContent').addClass('none');
			zm('._btnTab').removeClass('active');
			return false;
		});
		if (zm('#_btnShareShw').size()) {
			addthis_config = {
				"data_track_clickback":true, 
				ui_use_css : true, 
				addthis_brand: 'Zing MP3'
			};
			zmCore.addScript('http://s7.addthis.com/js/250/addthis_widget.js?ui_use_css=false&pub=khicontn');
		}
		/* Share ZMe */
		if (zm('#_shareZMe').size() || zm('#_shareFZMe1').size() || zm('#_shareZMe2').size()) {
			zmCore.addScript('http://wb.me.zing.vn/index.php?wb=LINK&t=js&c=share_button');
		}
		if(typeof MP3Label == 'object') MP3Label.load();
		if(typeof activeRingtoneFucntion == 'function') activeRingtoneFucntion();
		return false;
	},
	active:function(){
		if(MP3Tab.btnId){
			var tabBtn = zm('#'+MP3Tab.btnId);
			zm('._btnTab').removeClass('active');
			zm('._tabContent').addClass('none');
			var tab = tabBtn.addClass('active').attr('rel');
			zm('#'+tab).removeClass('none');
			switch(tab){
				case '_tabEmbed':
					var	strObj	= new Embed();
					// set embed code for forum and blog
					strObj.setEmbededCode();
					zm('#shr_btnAut').click(function(){
						strObj.changeAutoPlay();
					});
					zm('#shr_btnMubgr').click(function(){
						strObj.changeMusicBg();
					});
					break;
				case '_tabPlaylist':
					MP3Playlist.songID = tabBtn.attr('pid');
					if(!MP3.ACCOUNT_NAME){
						zm('._btnTab').removeClass('active');
						zm('._tabContent').addClass('none');
						Login.show(function(){
							MP3Tab.active();
						});
					} else {
						MP3Playlist.initTab();
					}
					break;
				case 'playlist':
					MP3Playlist.addFav('_addMsg',zm(this));
					break;
			}
		}
	}
};
zmCore.ready(function(){
	if(zm('#_videoPlayer').size()){
		if(zmCore.cookie('ZPexp')!=1) ZingPlayer.UnExpand();//zm('.sidebar').css('margin-top', '-465px');
		else ZingPlayer.Expand();
	}
	zm('#_suggestSMore').click(function(){
		var regEx = /\/([a-z0-9]+).html/i;
		var match = regEx.exec(location.pathname);
		_gaq.push(['mp3._trackPageview', location.pathname+'?'+zm(this).attr('tracking')]);
		if(match[1]){
			zmCore.get(MP3.MP3_URL+'ajax/suggest-song/get-more?id='+match[1]+'&start='+zm(this).attr('rel'),
			{'dataType':'json'},
			function(data){
				zm('#_suggestS').children('div').removeClass('last-child');
				zm('#_suggestS').append(data.html);
			});
		}
		zm(this).remove();
		return false;
	});
	MP3Lyrics.init();
	MP3SongPlay.init();
	MP3Player.init();
	MP3Tab.init();
});